<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');

class Pesan extends CI_Controller{
	var $_public_view;

	function __construct(){
		parent::__construct();
		$this->load->helper('url');
        $this->load->library('session');
        $this->config->load('ojexcom');
        $this->_public_view = $this->config->item('public_view');
	}

	function readMessage() {
		//cek session
		$isLogin = $this->session->userdata('isLogin');
		$user = '';
		if ($isLogin) {
			$user = $this->session->userdata('username');
			$id = $this->session->userdata('user_id');
		}

		$data_output['success'] = "false";

		$set_data = array(
			'unread' => 0,
		);
		$this->db->where('recipient', $id);
		$this->db->update('message', $set_data);
	}
	
	function index(){
		//cek session
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }
        $this->readMessage();
		$data_output['success'] = "true";
		$data_output['message'] = "";
		//$query = $this->db->query("SELECT u.name, u.id, m.sent_time FROM message m, user u WHERE m.recipient=".$id." AND u.id=m.sender GROUP BY u.name ORDER BY m.sent_time desc");
		// $sql = "select * from message, user where recipient = ? and message.sender = user.id group by message.sender order by sent_time";
		// $query = $this->db->query($sql,$id);
		// if($query->num_rows() > 0){
		// 	$row = $query->row(); 
		// 	$count = 0;
		// 	foreach($query->result() as $row){
		// 		$data_output['message'][$count]['senderId'] = $row->id;
		// 		$data_output['message'][$count]['senderName'] = $row->name;

		// 		$sql = "select * from message where sender = ? order by sent_time desc limit 1";
		// 		$query1 = $this->db->query($sql,$row->id);
		// 		$time = $query1->row();

		// 		$data_output['message'][$count]['sent_time'] = date('d-m-Y H:i',strtotime($time->sent_time));

		// 		$data_output['message'][$count]['senderAvatar'] = "";
		// 		$sql = "select avatar from user where id = ?";
		// 		$query1 = $this->db->query($sql,$row->id);
		// 		if($query1->num_rows() == 1){
		// 			$sender = $query1->row();
		// 			$data_output['message'][$count]['senderAvatar'] = $sender->avatar;
		// 		}
		// 		$count++;
		// 	}
		// }

		//$sql = "select sender, sent_time from message where recipient = ? order by sent_time desc";
		$sql = "select * from (select sender as sender, sent_time as sent_time from message where recipient = ? order by sent_time desc) as t group by sender order by sent_time desc";
		$query = $this->db->query($sql,$id);
		//print_r($query->result());
		if($query->num_rows() > 0){
			$row = $query->row(); 
			$count = 0;
			foreach($query->result() as $row){
				$data_output['message'][$count]['senderId'] = $row->sender;

				$sql = "select * from user where id = ?";
				$query1 = $this->db->query($sql,$row->sender);
				$row1 = $query1->row();
				$data_output['message'][$count]['senderName'] = $row1->name;

				// $sql = "select * from message where sender = ? order by sent_time desc limit 1";
				// $query1 = $this->db->query($sql,$row->id);
				// $time = $query1->row();

				$data_output['message'][$count]['sent_time'] = date('d-m-Y H:i',strtotime($row->sent_time));

				$data_output['message'][$count]['senderAvatar'] = "";
				$sql = "select avatar from user where id = ?";
				$query1 = $this->db->query($sql,$row->sender);
				if($query1->num_rows() == 1){
					$sender = $query1->row();
					$data_output['message'][$count]['senderAvatar'] = $sender->avatar;
				}
				$count++;
			}
		}
 
		$sql = "select * from message where recipient = ? order by sent_time desc limit 1";
		$query = $this->db->query($sql,$id);
		if($query->num_rows()<1){
			$data_output['detail_message'] = "";
		} else {
			$other = $query->row();
			$other_id = $other->sender;
			$sql = "select name from user where id = ?";
			$query = $this->db->query($sql,$other_id);
			$data_output['sender']['name'] = $query->row()->name;
			$data_output['sender']['id'] = $other_id;
			$query = $this->db->query("SELECT u.id, u.name, m.body, m.sent_time FROM message m, user u WHERE (u.id=m.sender AND m.recipient=".$id." AND m.sender=".$other_id.") OR (u.id=m.sender AND m.recipient=".$other_id." AND m.sender=".$id.") ORDER BY m.sent_time");
			$i = 0;
			if ($query->num_rows() < 1) {
				$data_output["detail_message"] = "";
	        } else {
				$row = $query->row();
				foreach($query->result() as $row){
					$data_output["detail_message"][$i]["senderId"] = $row->id;
					$data_output["detail_message"][$i]["senderName"] = $row->name;
					$data_output["detail_message"][$i]["body"] = $row->body;
					$data_output["detail_message"][$i]["sent_time"] = $row->sent_time;

					$data_output['detail_message'][$i]['senderAvatar'] = "";
					$sql = "select avatar from user where id = ?";
					$query1 = $this->db->query($sql,$row->id);
					if($query1->num_rows() == 1){
						$sender = $query1->row();
						$data_output['detail_message'][$i]['senderAvatar'] = $sender->avatar;
					}

					$i++;
				}
			}
		}

		$data = array(
				'data' => $data_output,
				'page_title' => 'Pesan',
				'page_content' => 'pesan',
				'isLogin' => $isLogin, 'user'=>$user, 'id' => $id
					);
		$this->load->view($this->_public_view, $data);
	}

	function send() {
		//cek session
		$isLogin = $this->session->userdata('isLogin');
		$user = '';
		if ($isLogin) {
			$user = $this->session->userdata('username');
			$id = $this->session->userdata('user_id');
		}

		$data_output['success'] = "false";

		$input_data = array(
			'sender' => $id,
			'recipient' => $this->input->post('recipient'),
			'body' => $this->input->post('body')
		);
		$this->db->insert('message', $input_data);
		$data_output['success'] = "true";
		// echo json_encode($data_output);
		//redirect('home','refresh');
	}

	function send_message(){
		//cek segment
        $str_id = '';
        if ($this->uri->segment(3) == FALSE) {
            redirect('home', 'location');
        } else {
            $str_id = $this->uri->segment(3);
        }

		$this->send();
		echo "Silakan tunggu ...";
		redirect('profil/detail/'.$str_id,'refresh');
	}
	
    function load($other_id) {
		//cek session
        $isLogin = $this->session->userdata('isLogin');
        $id=-1;
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }
		$query = $this->db->query("SELECT u.id, u.name, m.body, m.sent_time FROM message m, user u WHERE (u.id=m.sender AND m.recipient=".$id." AND m.sender=".$other_id.") OR (u.id=m.sender AND m.recipient=".$other_id." AND m.sender=".$id.") ORDER BY m.sent_time");
		$i = 0;
		if ($query->num_rows() < 1) {
			$data_output["message"] = "";
        } else {
			$row = $query->row();
			foreach($query->result() as $row){
				$data_output["message"][$i]["senderId"] = $row->id;
				$data_output["message"][$i]["senderName"] = $row->name;
				$data_output["message"][$i]["body"] = $row->body;
				$data_output["message"][$i]["sent_time"] = $row->sent_time;

				$data_output['message'][$i]['senderAvatar'] = "";
				$sql = "select avatar from user where id = ?";
				$query1 = $this->db->query($sql,$row->id);
				if($query1->num_rows() == 1){
					$sender = $query1->row();
					$data_output['message'][$i]['senderAvatar'] = $sender->avatar;
				}

				$i++;
			}
		}
		$data_output["count"] = $i;
        echo json_encode($data_output);
     }

    function get(){
		//cek session
        $isLogin = $this->session->userdata('isLogin');
        $id=-1;
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }
		$query = $this->db->query("SELECT u.name, u.id, m.body, m.sent_time FROM message m, user u WHERE m.unread=1 AND m.recipient=".$id." AND u.id=m.sender ORDER BY m.sent_time desc");
		$i = 0;
		if ($query->num_rows() < 1) {
			$data_output["message"] = "";
        } else {
			$row = $query->row();
			foreach($query->result() as $row){
				$data_output["message"][$i]["sender"] = $row->name;
				$data_output["message"][$i]["body"] = $row->body;
				$data_output["message"][$i]["sent_time"] = $row->sent_time;

				$data_output['message'][$i]['senderAvatar'] = "";
				$sql = "select avatar from user where id = ?";
				$query = $this->db->query($sql,$row->id);
				if($query->num_rows() == 1){
					$sender = $query->row();
					$data_output['message'][$i]['senderAvatar'] = $sender->avatar;
				}

				$i++;
			}
		}
		$data_output["count"] = $i;

		$query = $this->db->query("SELECT DISTINCT n.id AS notification_id, n.need_response, s.`status`,s.timeStamp, t.* FROM notifications n JOIN transactionstatus s ON n.transactionStatusId=s.id JOIN `transaction` t ON s.idTransaction=t.id WHERE n.status = 0 AND n.userId = ".$id." order by s.timeStamp desc");
		$count = -1;
		if($query->num_rows() > 0){
			$row_notif = $query->row(); 
			$count++;
			foreach($query->result() as $row_notif){
				if($row_notif->userId > 0 && $row_notif->providerId > 0){
					$count++;
				}
			}
		}
		$query_premium = $this->db->query("SELECT * FROM notifications WHERE type LIKE 'P' AND status = 0 AND userId =  ".$id);
		if($query_premium->num_rows() > 0){
			$count++;
		}
		$data_output['countNotif'] = $count;

		//$data_output['notifications'] = $this->getNotifications($id);	
		$data_output['notifications'] = "";
		$query = $this->db->query("SELECT DISTINCT n.id AS notification_id, n.need_response, s.`status`,s.timeStamp, t.* FROM notifications n JOIN transactionstatus s ON n.transactionStatusId=s.id JOIN `transaction` t ON s.idTransaction=t.id WHERE n.status = 0 AND n.userId = ".$id." order by s.timeStamp desc");
		if($query->num_rows() > 0){
			$row_notif = $query->row(); 
			$count = 0;
			foreach($query->result() as $row_notif){
				if($row_notif->userId > 0 && $row_notif->providerId > 0){
					$data_output['notifications']['transaction'][$count]['notification_id'] = $row_notif->notification_id;
					$data_output['notifications']['transaction'][$count]['timeStamp'] = $row_notif->timeStamp;
					$data_output['notifications']['transaction'][$count]['need_response'] = $row_notif->need_response;
					$data_output['notifications']['transaction'][$count]['idTransaction'] = $row_notif->id;
					$data_output['notifications']['transaction'][$count]['userId'] = $row_notif->userId;
					$data_output['notifications']['transaction'][$count]['userName'] = $this->getNameById($row_notif->userId);
					$data_output['notifications']['transaction'][$count]['userAvatar'] = $this->getAvatarById($row_notif->userId);
					$data_output['notifications']['transaction'][$count]['userLastUpdatedAvatar'] = $this->getLastUpdatedAvatar($row_notif->userId);
					$data_output['notifications']['transaction'][$count]['providerId'] = $row_notif->providerId;
					$data_output['notifications']['transaction'][$count]['providerName'] = $this->getNameById($row_notif->providerId);
					$data_output['notifications']['transaction'][$count]['providerAvatar'] = $this->getAvatarById($row_notif->providerId);
					$data_output['notifications']['transaction'][$count]['providerLastUpdatedAvatar'] = $this->getLastUpdatedAvatar($row_notif->providerId);
					//if($row_notif->need_response == 1){
						$data_output['notifications']['transaction'][$count]['departTime'] = $row_notif->departTime;
						$data_output['notifications']['transaction'][$count]['source_label'] = $row_notif->source_label;
						$data_output['notifications']['transaction'][$count]['source_latitude'] = $row_notif->source_latitude;
						$data_output['notifications']['transaction'][$count]['source_longitude'] = $row_notif->source_longitude;
						$data_output['notifications']['transaction'][$count]['destination_label'] = $row_notif->destination_label;
						$data_output['notifications']['transaction'][$count]['destination_latitude'] = $row_notif->destination_latitude;
						$data_output['notifications']['transaction'][$count]['destination_longitude'] = $row_notif->destination_longitude;
					//}
					$data_output['notifications']['transaction'][$count]['price'] = $row_notif->price;
					$data_output['notifications']['transaction'][$count]['paymentMethod'] = $row_notif->paymentMethod;
					$data_output['notifications']['transaction'][$count]['status'] = $row_notif->status;
					$count++;
				}
			}	
		}
		$query_premium = $this->db->query("SELECT * FROM notifications WHERE type LIKE 'P' AND status = 0 AND userId =  ".$id);
		if($query_premium->num_rows() > 0){
			$row_premium = $query_premium->row(); 
			$data_output['notifications']['premium'][0]['notification_id'] = $row_premium->id;
			$data_output['notifications']['premium'][0]['need_response'] = $row_premium->need_response;
			$data_output['notifications']['premium'][0]['userId'] = $row_premium->userId;
			$data_output['notifications']['premium'][0]['userName'] = $this->getNameById($row_premium->userId);
		}
		
        echo json_encode($data_output);
     }

     function getNotifications($id = ""){
		$data_output['success'] = "true";
		$data_output['notifications'] = "";
		$query = $this->db->query("SELECT DISTINCT n.id AS notification_id, n.need_response, s.`status`,s.timeStamp, t.* FROM notifications n JOIN transactionstatus s ON n.transactionStatusId=s.id JOIN `transaction` t ON s.idTransaction=t.id WHERE n.status = 0 AND n.userId = ".$id." order by s.timeStamp desc");
		if($query->num_rows() > 0){
			$row_notif = $query->row(); 
			$count = 0;
			foreach($query->result() as $row_notif){
				if($row_notif->userId > 0 && $row_notif->providerId > 0){
					$data_output['notifications']['transaction'][$count]['notification_id'] = $row_notif->notification_id;
					$data_output['notifications']['transaction'][$count]['timeStamp'] = $row_notif->timeStamp;
					$data_output['notifications']['transaction'][$count]['need_response'] = $row_notif->need_response;
					$data_output['notifications']['transaction'][$count]['idTransaction'] = $row_notif->id;
					$data_output['notifications']['transaction'][$count]['userId'] = $row_notif->userId;
					$data_output['notifications']['transaction'][$count]['userName'] = $this->getNameById($row_notif->userId);
					$data_output['notifications']['transaction'][$count]['userAvatar'] = $this->getAvatarById($row_notif->userId);
					$data_output['notifications']['transaction'][$count]['userLastUpdatedAvatar'] = $this->getLastUpdatedAvatar($row_notif->userId);
					$data_output['notifications']['transaction'][$count]['providerId'] = $row_notif->providerId;
					$data_output['notifications']['transaction'][$count]['providerName'] = $this->getNameById($row_notif->providerId);
					$data_output['notifications']['transaction'][$count]['providerAvatar'] = $this->getAvatarById($row_notif->providerId);
					$data_output['notifications']['transaction'][$count]['providerLastUpdatedAvatar'] = $this->getLastUpdatedAvatar($row_notif->providerId);
					//if($row_notif->need_response == 1){
						$data_output['notifications']['transaction'][$count]['departTime'] = $row_notif->departTime;
						$data_output['notifications']['transaction'][$count]['source_label'] = $row_notif->source_label;
						$data_output['notifications']['transaction'][$count]['source_latitude'] = $row_notif->source_latitude;
						$data_output['notifications']['transaction'][$count]['source_longitude'] = $row_notif->source_longitude;
						$data_output['notifications']['transaction'][$count]['destination_label'] = $row_notif->destination_label;
						$data_output['notifications']['transaction'][$count]['destination_latitude'] = $row_notif->destination_latitude;
						$data_output['notifications']['transaction'][$count]['destination_longitude'] = $row_notif->destination_longitude;
					//}
					$data_output['notifications']['transaction'][$count]['price'] = $row_notif->price;
					$data_output['notifications']['transaction'][$count]['paymentMethod'] = $row_notif->paymentMethod;
					$data_output['notifications']['transaction'][$count]['status'] = $row_notif->status;
					$count++;
				}
			}	
		}
		$query_premium = $this->db->query("SELECT * FROM notifications WHERE type LIKE 'P' AND status = 0 AND userId =  ".$id);
		if($query_premium->num_rows() > 0){
			$row_premium = $query_premium->row(); 
			$data_output['notifications']['premium'][0]['notification_id'] = $row_premium->id;
			$data_output['notifications']['premium'][0]['need_response'] = $row_premium->need_response;
			$data_output['notifications']['premium'][0]['userId'] = $row_premium->userId;
			$data_output['notifications']['premium'][0]['userName'] = $this->getNameById($row_premium->userId);
		}

		return $data_output;
     }

     function getNameById($userid){
		$query = $this->db->query("SELECT `name` FROM `user`WHERE `id`=".$userid);
		$row = $query->row();
		return $row->name;
	}
	
	function getAvatarById($userid){
		$query = $this->db->query("SELECT `avatar` FROM `user`WHERE `id`=".$userid);
		$row = $query->row();
		return $row->avatar;
	}
	
		
	function getLastUpdatedAvatar($userid){
		$query = $this->db->query("SELECT `lastUpdatedAvatar` FROM `user` WHERE `id`=".$userid."");
		$row = $query->row();
		return $row->lastUpdatedAvatar;
	}
}
